﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using MimeKit;
using MimeKit.Text;
using MKAdminCore.DTO.Web.Common;
using MKAdminCore.ToolKit.EmailHelper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace NetCoreWeb.Fileter
{
    public class ExceptionGlobalFilter : IExceptionFilter
    {
        readonly ILogger _iLogger;

        public ExceptionGlobalFilter(ILogger<ExceptionGlobalFilter> iLogger)
        {
            _iLogger = iLogger;
        }

        public void OnException(ExceptionContext context)
        {
            if (!context.ExceptionHandled)
            {
                _iLogger.LogError($"发生异常 {context.Exception.Message}");

                if (IsAjax(context.HttpContext.Request))
                {
                    var responseJson = new HttpResponseResult()
                    {
                        Code = (int)HttpResponseCode.InternalServerError,
                        Msg = "发生错误啦！"
                    };
                    context.Result = new OkObjectResult(responseJson);
                }
                else
                {
                    //_iLogger.LogError("页面请求错误");
                    context.Result = new RedirectResult("/error/index");
                }
                context.ExceptionHandled = true;

                //发送邮件通知
                var mailBoxAddress = new List<MailboxAddress>();
                mailBoxAddress.Add(new MailboxAddress("mikeit@163.com"));

                Task.Run(async () =>
                {
                    await EmailHelper.SendEMailAsync("MKAdmin异常通知", context.Exception.Message, mailBoxAddress, TextFormat.Html, exceptionWriteLog: false);
                });
            }
        }

        public bool IsAjax(HttpRequest req)
        {
            bool result = false;

            var xreq = req.Headers.ContainsKey("x-requested-with");
            if (xreq)
            {
                result = req.Headers["x-requested-with"] == "XMLHttpRequest";
            }

            return result;
        }
    }
}
